<?php
namespace User\Controller;
use Think\Controller;

class SemController extends Controller
{
    //发送
    public function index()
    {
      $z= $this->sub("18361130555");
      P($z);
    }  

    
    /**
     * [sub description]封装发送函数
     * @param  [type] $tel [手机号码]
     * @return [type]      [状态]
     */
    private function sub($tel)
    { 
      $sub_tel_code_len= cookie('sub_tel_code')? cookie('sub_tel_code'):0;
      if($sub_tel_code_len>= C("SUB_TEL_CODE_LEN")){ 
         return array("returnstatus"=>"Faild","message"=>"验证码提交次数过多!");
      }
      $post_data = array();
      $code= $this->GetRandStr();
      $post_data['userid'] = C("SEM_USER_ID");
      $post_data['account'] = C("SEM_USER_NAME");
      $post_data['password'] = C("SEM_USER_PASSWORD");
      $post_data['content'] = '您的验证码:'.$code.'，30分钟内有效，如非本人操作请忽略!'.C("SEM_USER_QM"); //短信内容需要用urlencode编码下
       
      $post_data['mobile'] = $tel;
      $post_data['sendtime'] = ''; //不定时发送，值为0，定时发送，输入格式YYYYMMDDHHmmss的日期值
      $url='http://sms.106vip.com/sms.aspx?action=send';
      $o='';
      foreach ($post_data as $k=>$v)
      {
      $o.="$k=".urlencode($v).'&';
      }
      $post_data=substr($o,0,-1);
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_HEADER, 0);
      curl_setopt($ch, CURLOPT_URL,$url);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //如果需要将结果直接返回到变量里，那加上这句。
      $result = curl_exec($ch);
      $data=xml_to_array($result);
      $z=$data['returnsms'];
      if($z["returnstatus"]=="Success"){
        cookie('sub_tel_code',$sub_tel_code_len+1,3600);
        $log = array(
           "tel"=>$tel,
           "code"=>$code,
           "ip"=>get_client_ip(),
           "sub_time"=>time(),
           "chack_time"=>time()+1800
          );
        M("sem_log")->add($log);
       }
      return $data['returnsms'];
    }
    

    /**
     * [GetRandStr description]
     * @param [type] $len [获取随机数]
     */
    private function  GetRandStr($len=null) 
    { 
      if(!$len){ 
          $len= C('SEM_CODE_LEN');
      }
      $chars = array( 
        "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" 
      ); 
      $charsLen = count($chars) - 1; 
      shuffle($chars);   
      $output = ""; 
      for ($i=0; $i<$len; $i++) 
      { 
          $output .= $chars[mt_rand(0, $charsLen)]; 
      }  
      return $output;  
    } 
 


}